package com.wc.controller;

import com.wc.pojo.User;
import com.wc.service.ExcelService;
import com.wc.service.UserService;
import com.wc.util.Page;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户控制层
 */
@Controller
public class UserController {
	
	@Autowired
	private UserService service;
	@Autowired
	private ExcelService excelService;

	protected static Logger logger = LoggerFactory.getLogger(UserController.class);

	@RequestMapping("/showUsers")
	@ResponseBody
	public Map<String, Object> getUserlist(@RequestParam(defaultValue = "1")int pageNo, @RequestParam(defaultValue = "5")int pageSize, @RequestParam(value = "name", required = false) String name, String isSort){
		Map<String, Object> map = new HashMap<String, Object>();
		Page<User> page = service.getUserlist(pageNo, pageSize, name, isSort);
		List<User> list = page.getList();
		Object[] userArray = {list,page.getPageNo(),page.getTotalCount(),page.getTotalPage()};
		logger.info("getUserlist===>封装数组长度==="+userArray.toString().length());
		//查到的数据和分页需要的参数用存到数组里，再存到map，最后转发json数据
		map.put("userArray",userArray);
		return map;
	}

	@RequestMapping(value = "/saveUser",method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> saveUser(@RequestBody User user) throws ParseException {
		Map<String, String> map = new HashMap<String, String>();
		logger.info("saveUser===>前端参数===>"+user);
		boolean result = service.saveUser(user);
		if (result){
			map.put("result","true");
		}else {
			map.put("result","false");
		}
		return map;
	}

	@RequestMapping("/validateUseridcard")
	@ResponseBody
	public Map<String, String> validateUseridcard(@RequestParam(value = "idcard") String idcard){
		Map<String, String> map = new HashMap<String, String>();
		logger.info("validateUseridcard===>前端参数===>"+idcard);
		boolean result = service.validateUseridcard(idcard);
		if (result){
			map.put("result","true");
		}else {
			map.put("result","false");
		}
		return map;
	}

	@RequestMapping( value = "/updateUser",method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> updateUser(@RequestBody User user){
		Map<String, String> map = new HashMap<String, String>();
		logger.info("updateUser===>前端参数===>"+user);
		boolean result = service.updateUser(user);
		if (result){
			map.put("result","true");
		}else {
			map.put("result","false");
		}
		return map;
	}

	@RequestMapping("/removeUser")
	@ResponseBody
	public Map<String, String> removeUser(@RequestParam(value = "idcard") String idcard){
		Map<String, String> map = new HashMap<String, String>();
		logger.info("removeUser>===前端参数===>"+idcard);
		boolean result = service.removeUser(idcard);
		if (result){
			map.put("result","true");
		}else {
			map.put("result","false");
		}
		return map;
	}

	@RequestMapping("/getUseridcard")
	@ResponseBody
	public Map<String, User> getUseridcard(@RequestParam(value = "idcard") String idcard){
		Map<String, User> map = new HashMap<String, User>();
		logger.info("getUseridcard===>前端参数===>"+idcard);
		User user = service.getUseridcard(idcard);
		map.put("user",user);
		return map;
	}

	@RequestMapping("/getUserById")
	@ResponseBody
	public Map<String, User> getUserById(@RequestParam(value = "userid") Integer userid){
		Map<String, User> map = new HashMap<String, User>();
		logger.info("getUserById===>前端参数===>"+userid);
		User user = service.getUserById(userid);

		map.put("user",user);
		return map;
	}

	@RequestMapping(value="ajaxUpload", produces = "application/text; charset=utf-8",method = RequestMethod.POST)
	@ResponseBody
	public String UploadExcel(@RequestParam(value = "upfile",required = false) MultipartFile file){
		String msg = null;
		try {
			msg = excelService.ajaxUploadExcel(file);
			return msg;
		} catch (Exception e) {
			System.err.println(e.getMessage());
			logger.debug(e.getMessage());
		}
		return "0";
	}

	@RequestMapping(value = "downloadExcel",method = RequestMethod.POST)
	public void downloadExcel(HttpServletRequest request,HttpServletResponse response){
		//导出Excel对象
		XSSFWorkbook workbook = null;
		OutputStream output = null;
		BufferedOutputStream bufferedOutput = null;
		try {
			response.reset(); //清除buffer缓存
			//Map<String,Object> map=new HashMap<String,Object>();
			// 指定下载的文件名
			response.setContentType("application/vnd.ms-excel;charset=UTF-8");
			response.setHeader("Content-Disposition","attachment;filename="+new String("用户表.xlsx".getBytes(),"iso-8859-1"));
			//将查到的数据用XSSFWorkbook保存并创建一个流
			workbook = excelService.exportExcelInfo();
			output = response.getOutputStream();
			bufferedOutput = new BufferedOutputStream(output);
			bufferedOutput.flush();
			//最后通过流写进去
			workbook.write(bufferedOutput);
		} catch (Exception e) {
			System.err.println(e.getMessage());
			logger.debug(e.getMessage());
		}finally {
			try {
				bufferedOutput.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	

}
